package wiki.liven.utils;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by leven on 2017/1/11.
 */
public class ListUtil {

    /**
     * 提取集合中的对象的任意属性的值，组成一个新的集合。
     * P.S.目前仅支持String类型的提取
     * @param collections
     * @param propertyName
     * @param <T>
     * @return
     */
    public static <T> List<String> selectOnePropertyFromCollections(List<T> collections,String propertyName){
        List<String> response;
        response = new ArrayList<>();
        for (T t:collections) {
            Class<T> clazz = (Class<T>) t.getClass();
            PropertyDescriptor propertyDescriptor;
            try {
                propertyDescriptor = new PropertyDescriptor(propertyName,clazz);
                Method getMethod = propertyDescriptor.getReadMethod();
                String value = (String) getMethod.invoke(t);
                response.add(value);
            } catch (IntrospectionException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return response;
    }



}
